package rad.framework.seam;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;

import rad.framework.validator.Unique;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.hibernate.annotations.NaturalId;
import org.hibernate.validator.NotNull;

@Entity
@Unique(message="RefEntity name must be unique.")
public class RefEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	private Long id;
	private String name;

	@Id
	@GeneratedValue
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	@NaturalId
	@NotNull
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	private RefEntity parent;
	
	@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.MERGE)
	public RefEntity getParent() {
		return parent;
	}

	public void setParent(RefEntity parent) {
		this.parent = parent;
	}
	
	private Set<RefEntity> related;
		
	@ManyToMany(cascade=CascadeType.MERGE)
	public Set<RefEntity> getRelated() {
		if (related == null) {
			related = new HashSet<RefEntity>();
		}
		return related;
	}

	public void setRelated(Set<RefEntity> related) {
		this.related = related;
	}
	
	public void addRelated(RefEntity related) {
		getRelated().add(related);
	}
	
	public String toString() {
		return ToStringBuilder.reflectionToString(this,
				ToStringStyle.MULTI_LINE_STYLE);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? super.hashCode() : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		RefEntity other = (RefEntity) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
	
}
